import {
  EwmCodeLogin,
  Loginout,
  quickLoginApi,
  getIMUserSigApi,
} from '@/api/login/login'
import {  getUserInfo,postUserEdit } from '@/api/user'
import {
  changeAvatarApi,
  changeUserPhoneApi,
  closeAccountApi,
  updateInfoApi,
  getNoreadMessageNum,
} from '@/api/user/user.js'
// import {
//   getUserPetList,
//   homePetData,
//   getPetScore,
//   freePetFood,
// } from '@/api/pet/pet.js'
import {
  reportClientData,
  getAdvertisingBannerList,
} from '@/api/public/public.js'
// import { localHospital } from '@/api/medical/medical.js'
import { bindingRelation } from '@/api/home/home'
import cookie from '@/utils/store/cookie'
const user = {
  namespaced: true,
  state: {
    token: uni.getStorageSync('Token'),
    name: '',
    avatar: '',
    phone: '',
    showPetAction: 3, // 展示溜宠模块
    UserInfo: {},
    walkData: null, // 溜宠数据
    waitData: null, // 陪宠数据
    petFoodStatus: false,
    score: 0, // 宠气值
    petList: null, // 宠物列表
    albumList: null, // 相册列表
    address: null, // 用户所在城市
    noReadNum: 0, // 用户未读消息数
    hospitalList: [],
    birthdayStr: '', // 生日宠物列表
    userCount: null,
    walkAderImg: '', // 溜宠背景图
    showLocation: true, //是否弹出获取位置授权弹窗
    noMoreShowLocation: false, //不再提示获取位置授权弹窗
    UserAddress: null,
    isIOS: false,
    localHistoryTextList: [], // AI问诊 智能助手 问题
    localIndex: 0, // AI问诊 智能助手 问题
    localPet: {
      type: '',
      age: '',
      sex: '',
      repellent: '',
      vaccine: '',
    },
  },

  mutations: {
    SET_ISIOS: (state, data) => {
      state.isIOS = data
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_U_ADDRESS: (state, data) => {
      state.UserAddress = data
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PHONE: (state, phone) => {
      state.phone = phone
    },
    USERINFO: (state, userInfo) => {
      state.UserInfo = userInfo
    },
    SET_ADDRESS: (state, data) => {
      state.address = data
    },
    SET_SHOWLOCATION: (state, data) => {
      state.showLocation = data
    },
    SET_NOMORESHOWLOCATION: (state, data) => {
      state.noMoreShowLocation = data
    },
    SET_PETLIST: (state, data) => {
      state.petList = data
    },
    SET_NOREADNUM: (state, data) => {
      state.noReadNum = data
    },
    SET_HOSPITALLIST: (state, data) => {
      state.hospitalList = data
    },
    SET_BIRTHDATSTR: (state, data) => {
      state.birthdayStr = data
    },
    SET_USERCOUNT: (state, data) => {
      state.userCount = data
    },
    SET_ALBUMLIST: (state, data) => {
      state.albumList = data
    },
    SET_SCORE: (state, data) => {
      state.score = data
    },
    SET_WALKDATA: (state, data) => {
      state.walkData = data
    },
    SET_PETFOODSTATUS: (state, data) => {
      state.petFoodStatus = data
    },
    SET_WAITDATA: (state, data) => {
      state.waitData = data
    },
    SET_walkAderImg: (state, data) => {
      state.walkAderImg = data
    },
    SET_showPetAction: (state, data) => {
      state.showPetAction = data
    },
    SET_localHistoryTextList: (state, data) => {
      state.localHistoryTextList = data
    },
    SET_localIndex: (state, data) => {
      state.localIndex = data
    },
    SET_localPet: (state, data) => {
      state.localPet = data
    },
  },
  actions: {
    //IM 登录
    IMLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        getIMUserSigApi()
          .then(res => {
            console.log('IM签名获取成功', res)
            if (!uni.$TUIKit) return
            uni.$TUIKit
              .login({
                userID: uni.getStorageSync('UserInfo').id + '',
                userSig: res,
              })
              .then(() => {
                uni.setStorageSync('isIMLogin', true)
                console.log('im登錄成功')
                resolve(res)
              })
              .catch(error => {
                console.log('im登錄失敗', error)
                reject(error)
              })
          })
          .catch(error => {
            console.log('IM签名获取失败', res)
            reject(error)
          })
      })
    },

    //手机验证码登录
    CodeLogin({ commit, dispatch }, userInfo) {
      const phone = userInfo.phone
      const phoneCode = userInfo.phoneCode
      return new Promise((resolve, reject) => {
        EwmCodeLogin(phone, phoneCode)
          .then(res => {
            uni.setStorageSync('Token', res.token)
            commit('SET_TOKEN', res.token)
            reportClientData()
            dispatch('toGetPosition')
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 退出系统
    Logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        Loginout()
          .then(() => {
            //uni.$TUIKit.logout().then(() => {})
            commit('SET_TOKEN', '')
            commit('USERINFO', null)
            commit('SET_PHONE', null)
            commit('SET_AVATAR', null)
            commit('SET_NAME', null)
            commit('SET_ADDRESS', null)
            commit('SET_U_ADDRESS', null)
            commit('SET_PETLIST', null)
            commit('SET_ALBUMLIST', null)
            commit('SET_NOREADNUM', 0)
            commit('SET_BIRTHDATSTR', '')
            commit('SET_HOSPITALLIST', [])
            commit('SET_WALKDATA', null)
            commit('SET_WAITDATA', null)
            commit('SET_SCORE', 0)
            // uni.clearStorageSync()
            uni.removeStorageSync('Token')
            uni.removeStorageSync('UserInfo')
            uni.removeStorageSync('showBirthday')
            // uni.preLogin({
            //   provider: 'univerify',
            //   success(res) {
            //     uni.setStorageSync('preLogin', 'success')
            //     console.log('预登录---success成功-Logout')
            //   },
            //   fail(res) {
            //     // 预登录失败
            //     // 不显示一键登录选项（或置灰）
            //     // 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
            //     uni.setStorageSync('preLogin', 'fail')
            //     console.log(res, '预登录---fail失败')
            //   },
            // })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    async GetUserInfo({ state, commit }, data) {
      try {
        console.log("看这里")
        const res = await getUserInfo()
        console.log(111111)
        console.log(res)
        console.log(3333)
        //let numRes = await getNoreadMessageNum()---接口不通
        uni.setStorageSync('UserInfo', res)
        console.log('====================用户信息3', res)
        if (uni.getStorageInfoSync('isJump')) uni.removeStorageSync('isJump')
        console.log('====================用户信息2', res)
        // 绑定分销参数
        // let urlSpread = cookie.get('spread')
        // if (urlSpread) {
        //   bindingRelation(urlSpread).then()
        // }
        commit('USERINFO', res.data)
        commit('SET_NAME', res.data.nickname)
        commit('SET_AVATAR', res.data.avatar)
        commit('SET_PHONE', res.data.phone)
        //commit('SET_NOREADNUM', numRes)
      } catch (err) {
        console.log(99999)
        console.log(err)
      }
    },
    // 修改用户头像
    async changeAvatar({ commit }, data) {
      const res = await changeAvatarApi(data)
      return res
    },
    // 修改用户信息
    async updateInfo({ commit }, data) {
      const res = await postUserEdit(data)
      return res
    },
    // 修改绑定手机号
    async changeUserPhone({ commit }, data) {
      const res = await changeUserPhoneApi(data)
      return res
    },
    // 注销账号 删除账号
    async closeAccount({ commit }) {
      const res = await closeAccountApi()
      return res
    },
    
    // 登录后请求
    //为了解决一键登录后ios首页不会执行onshow方法
    async loginIn({ dispatch }) {
      // 背景图
      dispatch('getWalkBg')
      // 宠物列表
      dispatch('getPetList')
      // // 宠气值
      // dispatch('getScore')
      // // 相册列表
      // // dispatch('getUserAlbumList')
      // // 溜宠数据
      // dispatch('getPetData', 1)
      // dispatch('getPetData', 2)
      // dispatch('getPetStatus')
      // // 获取位置 ios 与 安卓差异 ios 会在关闭一键登录 弹窗后 执行位置授权弹窗
      // if(uni.getSystemInfoSync().platform == "ios") dispatch('toGetPosition')
    },
  },
}

export default user
